<?php
namespace App\Console\Commands;

use App\Models\Achievement;
use App\Models\Attendance;
use \App\Models\Keys;
use App\Models\RewardPunishDetail;
use Illuminate\Console\Command;

use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use App\Models\User;
use App\Models\UserPerformance;
use App\Models\UserPerformanceMonth;


class WebsocketTest extends Command
{
    protected $signature = 'WebsocketTest';

    protected $description = 'webso';
    public $server;
    public function __construct() {
        parent::__construct();
        $this->server = new \swoole_websocket_server("0.0.0.0", 9501);
        $this->server->on('open', function (\swoole_websocket_server $server, $request) {
            $key = Keys::where('name','userid')->first();
            $this->server->push($request->fd, $key->name);
            echo "server: handshake success with fd{$request->fd}\n";
        });
        $this->server->on('message', function (Swoole\WebSocket\Server $server, $frame) {
            echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
            $server->push($frame->fd, "this is server");
        });
        $this->server->on('close', function ($ser, $fd) {
            echo "client {$fd} closed\n";
        });
        $this->server->on('request', function ($request, $response) {
            // 接收http请求从get获取message参数的值，给用户推送
            // $this->server->connections 遍历所有websocket连接用户的fd，给所有用户推送
            foreach ($this->server->connections as $fd) {
                $this->server->push($fd, $request->get['message']);
            }
        });
        $this->server->start();
    }
}
//new WebsocketTest();

